package com.cdks.wuxiu.api.service;

import com.cdks.wuxiu.api.component.cdks.kmsg.SingleMessage;
import com.cdks.wuxiu.api.component.constant.Constant;
import com.cdks.wuxiu.api.component.constant.ScoreEnum;
import com.cdks.wuxiu.api.service.mysql.DailySystemInfoService;
import com.cdks.wuxiu.api.service.mysql.RechargeOrderInfoService;
import com.cdks.wuxiu.api.service.mysql.RechargePriceConfigService;
import com.cdks.wuxiu.api.service.mysql.ScoreAwardConfigService;
import com.cdks.wuxiu.api.service.mysql.UserBaseInfoService;
import com.cdks.wuxiu.api.service.mysql.UserBillInfoService;
import com.cdks.wuxiu.api.service.mysql.UserScoreInfoService;
import com.cdks.wuxiu.api.service.mysql.UserWalletInfoService;
import com.cdks.wuxiu.api.util.TimeUtils;
import com.cdks.wuxiu.entity.message.ChatPrivateData;
import com.cdks.wuxiu.entity.mysql.RechargeOrderInfo;
import com.cdks.wuxiu.entity.mysql.RechargePriceConfig;
import com.cdks.wuxiu.entity.mysql.ScoreAwardConfig;
import com.cdks.wuxiu.entity.mysql.UserBaseInfo;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalTime;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;


/**
 * 充值信息表 服务实现类
 */
@Slf4j
@Service
public class RechargeServiceImpl implements RechargeService {
    @Resource
    private RechargePriceConfigService rechargePriceConfigService;
    @Resource
    private RechargeOrderInfoService rechargeOrderInfoService;
    @Resource
    private UserWalletInfoService userWalletInfoService;
    @Resource
    private UserBaseInfoService userBaseInfoService;    
    @Resource
    private UserBillInfoService userBillInfoService;
    @Resource
    private ScoreAwardConfigService scoreAwardConfigService;
    @Resource
    private UserScoreInfoService userScoreInfoService;
    @Resource
    private DailySystemInfoService dailySystemInfoService;


    private int saveAwardBill(long cost, long payerId, long earnerId, long orderId, String remark)
    {       
        int ret  = userBillInfoService.saveBill(cost, cost, 0, cost, cost, payerId, earnerId, Constant.COST_TYPE_SCORE, Constant.COST_TYPE_SCORE, orderId, remark);
        if (ret < 0)
        {
            log.error("recharge reward save bill failed");

            return -1;
        }

        return 0;
    }

    private int rewardScore(long userId, UserBaseInfo inviter, long cost, ScoreEnum type, long orderId)
    {
        //获取积分奖励配置
        ScoreAwardConfig config  = scoreAwardConfigService.getByType(type.getCode());
        if ((config == null) || (config.getStartTime().compareTo(LocalTime.now()) > 0) || (config.getStopTime().compareTo(LocalTime.now()) < 0))
        {
            return -1;
        }
        
        long score  = (cost * config.getScore() / 1000) * 10;

        //给邀请人发放奖励
        long expire  = TimeUtils.getTimeSecond() + config.getExpire();
        userScoreInfoService.addScore(inviter.getUserId(), score, type.getCode(), expire, type.getDesc());
        //保存邀请人积分账单
        saveAwardBill(score, userId, inviter.getUserId(), orderId, type.getDesc());

        //给用户发送通知
        ChatPrivateData data  = new ChatPrivateData();
        data.setContent("您有" + score + "积分到账，可消费也可提现，有效期至" + TimeUtils.getLocalDateTime("yyyy-MM-dd HH:mm:ss", expire));
        SingleMessage.sendChatMessage(Constant.USERID_SYSTEM, inviter.getUserId(), Constant.MSG_TYPE_TEXT, Constant.ENABLE_NO, data);

        return 0;
    }

    private int rewardInviter(long userId, long bean, long orderId)
    {
        //查找用户的邀请人
        UserBaseInfo inviter  = userBaseInfoService.getInviterInfo(userId);
        if ((inviter != null) && (inviter.getType() < Constant.ACCOUNT_TYPE_PLAT))
        {
            rewardScore(userId, inviter, bean, ScoreEnum.TYPE_INVITED_RECHARGE, orderId);
        }

        return 0;
    }

    @Override
    public List<RechargePriceConfig> getPriceList(int branch) {
        int min  = 0;
        int max  = 0;


        if (branch == 310)
        {
            min  = 500;
            max  = 600;
        }
        else
        {
            min  = 100;
            max  = 400;
        }

        return rechargePriceConfigService.getList(min, max - 1);
    }

    @Override
    public RechargeOrderInfo createOrder(long userId, int branch, int priceId, int type) {
        RechargePriceConfig price  = rechargePriceConfigService.getByPriceId(priceId);
        RechargeOrderInfo order  = new RechargeOrderInfo();

        order.setCreateTime(TimeUtils.getTimeSecond());
        order.setUserId(userId);
        order.setMoney(price.getMoney());
        order.setPriceId(price.getPriceId());
        order.setBean(price.getBean() + price.getPlus());
        order.setOrderNo("WXC" + TimeUtils.getLocalDateTime("yyyyMMddHHmmssSSS") + userId);
        order.setBranch(branch);
        order.setType(type);

        rechargeOrderInfoService.save(order);
        
        return order;
    }

    @Override
    public RechargeOrderInfo getOrderByOrderNo(String orderNo) {
        return rechargeOrderInfoService.getByOrderNo(orderNo);
    }

    @Override
    public RechargeOrderInfo getOrderByThirdNo(String thirdNo) {
        return rechargeOrderInfoService.getByThirdNo(thirdNo);
    }

    @Override
    public RechargeOrderInfo getOrderByPriceIdWithStatus(String priceId, int status) {
        return rechargeOrderInfoService.getByPriceIdWithStatus(priceId, status);
    }

    @Override
    public RechargeOrderInfo getOrderByOrderNoWithStatus(String orderNo, int status) {
        return rechargeOrderInfoService.getByOrderNoWithStatus(orderNo, status);
    }

    @Override
    public int payOrderSuccess(RechargeOrderInfo order) {
        int ret  = rechargeOrderInfoService.updateByStatus(order, Constant.PAY_STATUS_NOPAY);
        if (ret < 0)
        {
            return -1;
        }

        ret  = userWalletInfoService.addBean(order.getUserId(), order.getBean(), Constant.STATIS_TYPE_RECHARGE);
        if (ret < 0)
        {
            return -2;
        }

        dailySystemInfoService.addRechargeCost(order.getMoney());
        rewardInviter(order.getUserId(), order.getBean(), order.getId());

        return 0;
    }

    @Override
    public List<RechargeOrderInfo> getRecord(long userId, int page, long start, long stop) {
        return rechargeOrderInfoService.getRecord(userId, page, start, stop);
    }  
}
